package cnki.kg.algorithm;

import org.junit.jupiter.api.Test;

public class MoveZeroes {
    @Test
    public void test(){
        int[] nums=new int[]{0,1,0,3,12};
        moveZeroes2(nums);
    }
    public void moveZeroes(int[] nums) {
        int index=0;
        for (int i = 0; i <nums.length; i++) {
            if(nums[i]!=0){
                nums[index]=nums[i];
                index++;

            }
        }
        for (int i = index; i<nums.length; i++) {
            nums[i]=0;
        }
    }
    public void moveZeroes2(int[] nums) {
        if (nums == null) {
            return;
        }
        //两个指针i和j
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            //当前元素!=0，就把其交换到左边，等于0的交换到右边
            if (nums[i] != 0) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                j++;
            }
        }
    }

}
